package Concurrency2.Chapter01_Base;

import java.util.concurrent.TimeUnit;

/**
 * Instruction：验证线程的优先级, 是否优先级高的, 就一定能先执行
 * Author：@author MaLi
 */
public class T05_Priority {
    //定义10个不同优先级的线程 - 任务是累加

    static class PriorityClass extends Thread {
        long times = 0L;


        @Override
        public void run() {
            while (true) {
                times++;
            }
        }

        //用于获取执行的次数
        public long getTimes() {
            return times;
        }
    }


    //创建10个线程并启动
    public static void main(String[] args) {
        PriorityClass[] threads = new PriorityClass[10];
        int priority = 0;
        for (int i = 0; i < 10; i++) {
            threads[i] = new PriorityClass();
            threads[i].setPriority(++priority);
        }
        for (Thread thread : threads) {
            thread.start();
        }

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        for (Thread thread : threads) {
            thread.stop();
        }

        for (PriorityClass thread : threads) {
            System.out.println(thread.getName() + "---> priority: " + thread.getPriority() + " -->执行次数" + thread.getTimes());
        }
    }
}
